﻿using Microsoft.AspNetCore.Mvc;
using MySqlDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MySqlDemo.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class PeopleController : ControllerBase
    {
        private readonly MyDbContext _dbContext;
        public PeopleController(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Create()
        {
            using (_dbContext)
            {
                var person = new Person
                {
                    Name = "Rector",
                    // LastName = "Liu",
                    // CreatedAt = DateTime.Now
                };
                _dbContext.People.Add(person);
                _dbContext.SaveChanges();
            }
            return Ok();
        }

        /// <summary>
        /// 读取指定Id的数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("{id:int}")]
        public IActionResult GetById([FromRoute] int id)
        {
            using (_dbContext)
            {
                var list = _dbContext.People.Find(id);
                return Ok(list);
            }
        }

        /// <summary>
        /// 读取所有
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("")]
        public IActionResult GetAll()
        {
            using (_dbContext)
            {
                throw new Exception();
                var list = _dbContext.People.ToList();
                return Ok(list);
            }
        }
    }
}
